package uc

import (
	log "github.com/sirupsen/logrus"
	"net"
	"sync"
)

var mutex sync.Mutex

type Client struct {
	Conn net.Conn
}

func (client *Client) Write(addr string, body []byte) {
	// TODO 看下是否能优化
	client.connect(addr)
	if client.Conn != nil {
		_, err := client.Conn.Write(body)
		if err != nil {
			log.Error(err)
			client.Conn.Close()
			client.Conn = nil
			client.connect(addr)
		}
	}
}

func (client *Client) connect(addr string) {
	if client.Conn == nil {
		mutex.Lock()
		if client.Conn == nil {
			tcpAddr, err := net.ResolveTCPAddr("tcp4", addr)
			if err != nil {
				log.Println(err)
			}
			client.Conn, err = net.DialTCP("tcp4", nil, tcpAddr)
			if err == nil {
				go func() {
					HandleClientTcpCon(client.Conn, ReceiveChan, 65536)
				}()
			} else {
				client.Conn = nil
			}
		}
		mutex.Unlock()
	}
}
